package cn.com.backstage.controller;

import java.io.File;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.ApiGoods_p;
import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiT_city;
import cn.com.api.entity.ApiType;

import cn.com.api.service.ApiT_cityService;
import cn.com.api.service.ApiShopsService;
import cn.com.api.service.ApiTypeService;
import cn.com.api.service.StartOnLoadService;

import cn.com.util.ImageUtils;
import cn.com.util.Tools;
import cn.com.util.*;
import cn.com.util.*;
import cn.com.util.*;
import cn.com.util.*;
import cn.com.util.*;

@Controller
@RequestMapping(Utils.SYS_BACKSTAGE + "/")
public class T_shopController {

	private static Logger logger = Logger.getLogger(T_shopController.class);

	@Autowired
	private ApiShopsService apiShopsService;
	@Autowired
	private ApiT_cityService apiT_cityService;
	@Autowired
	private ApiTypeService apiTypeService;
	@Autowired
	private StartOnLoadService startOnLoadService;

	/**
	 * 进入查询界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "shop-list")
	public ModelAndView shop_list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/shop_list.jsp");
		//
		List<ApiShop> shops = apiShopsService.findShopsAll();
		mv.addObject("shops", shops);

		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> types = apiTypeService.getFirstTypes();
		List<ApiType> types2 = new ArrayList<ApiType>();
		// 包含根级分类
		types2.addAll(types);
		List<ApiType> types22 = apiTypeService.getSecondTypes();
		types2.addAll(types22);
		mv.addObject("types", types2);
		Map<String, Object> cond = new HashMap<String, Object>();
		cond.put("status", "2");
		mv.addObject("cond", cond);

		//
		if (request.getParameter("id") != null) {
			String id = request.getParameter("id");
			ApiShop shop = apiShopsService.findShopByCid(id);
			mv.addObject("shop", shop);
		}

		return mv;
	}

	/**
	 * 条件查询
	 * 
	 * @return
	 */
	@RequestMapping(value = "shop-condition")
	public ModelAndView shop_condition(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/shop_list.jsp");
		String status = request.getParameter("status");// 店铺状态
		if (status == null) {
			status = "1";
		}
		status = status.length() > 0 ? status : "1";
		String name = request.getParameter("name");// 名称
		String id = request.getParameter("id");// id
		String c_contacts = request.getParameter("c_contacts");// 联系人
		String phone = request.getParameter("phone");// 联系电话
		String type = request.getParameter("type");// 品类
		String cashType = request.getParameter("cashType");// 结款方式
		String address = request.getParameter("address");// 地址
		String is_ziying = request.getParameter("is_ziying");// 自否自营
		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> types = apiTypeService.getFirstTypes();
		List<ApiType> types2 = new ArrayList<ApiType>();
		// 包含根级分类
		types2.addAll(types);
		List<ApiType> types22 = apiTypeService.getSecondTypes();
		types2.addAll(types22);
		mv.addObject("types", types2);
		Map<String, Object> cond = new HashMap<String, Object>();
		cond.put("status", status);
		cond.put("name", name);
		cond.put("id", id);
		cond.put("c_contacts", c_contacts);
		cond.put("phone", phone);
		cond.put("type", type);
		cond.put("cashType", cashType);
		cond.put("address", address);
		if(is_ziying==null)
			cond.put("is_ziying", 0);
		else
			cond.put("is_ziying", is_ziying);
		
		List<ApiShop> shops = apiShopsService.searCondition(cond, pageInfo);
		mv.addObject("shops", shops);
		mv.addObject("cond", cond);
		mv.addObject("pageInfo", pageInfo);
		return mv;
	}

	/**
	 * 进入新增页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "shop-add-pre")
	public ModelAndView shop_add_pre(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/shop_add.jsp");
		//
		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> types = apiTypeService.getBigTypes();
		;
		/*
		 * List<ApiType> types2 = new ArrayList<ApiType>(); // 包含根级分类
		 * types2.addAll(types); List<ApiType> types22 =
		 * apiTypeService.getSecondTypes(); types2.addAll(types22);
		 */

		mv.addObject("waimai", startOnLoadService.dictionaryMap().get("MENU_MEISHI"));
		mv.addObject("xiandan", startOnLoadService.dictionaryMap().get("MENU_XIANHUADANGAO"));
		mv.addObject("shfw", startOnLoadService.dictionaryMap().get("MENU_FUWU"));

		mv.addObject("types", types);

		//
		if (request.getParameter("id") != null) {
			String id = request.getParameter("id");
			ApiShop shop = apiShopsService.findShopByCid(id);
			List<String> images = new ArrayList<String>();// 身份证
			List<String> images1 = new ArrayList<String>();// 其他证件
			if (shop.getcType() == -1) {
				mv.addObject("bigtype", "-1");
				mv.addObject("stype", "-1");
			} else {
				ApiType atype = apiTypeService.findTypeById(shop.getcType());
				mv.addObject("bigtype", atype.getcBelong() == 0 ? atype.getcCode() : atype.getcBelong());
				mv.addObject("stype", atype.getcCode());
			}
			if (shop.getImage1() != null) {
				for (String s : shop.getImage1().split(",")) {
					if (s.length() > 0) {
						images.add(s);
					}
				}
			}
			if (shop.getImage3() != null) {
				for (String s : shop.getImage3().split(",")) {
					if (s.length() > 0) {
						images1.add(s);
					}
				}
			}
			mv.addObject("imageList", images);
			mv.addObject("imageList1", images1);
			try{
				DecimalFormat df = new DecimalFormat("######0.00");
				shop.setDiscount(df.format((1 - Double.parseDouble(shop.getDiscount())) * 100));
			}catch(Exception e){}
		
			mv.addObject("shop", shop);
		}
		return mv;
	}

	/**
	 * 进入查看页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "shop-del-pre")
	public ModelAndView shop_del_pre(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/shop_detail.jsp");
		//
		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> types = apiTypeService.getFirstTypes();
		List<ApiType> types2 = new ArrayList<ApiType>();
		// 包含根级分类
		types2.addAll(types);
		List<ApiType> types22 = apiTypeService.getSecondTypes();
		types2.addAll(types22);

		mv.addObject("types", types2);

		if (request.getParameter("id") != null) {
			String id = request.getParameter("id");
			ApiShop shop = apiShopsService.findShopByCid(id);
			List<String> images = new ArrayList<String>();// 身份证
			List<String> images1 = new ArrayList<String>();// 其他证件

			ApiType atype = apiTypeService.findTypeById(shop.getcType());
			if (atype != null) {
				mv.addObject("bigtype", atype.getcBelong() == 0 ? atype.getcCode() : atype.getcBelong());
				mv.addObject("stype", atype.getcBelong() == 0 ? "" : atype.getcCode());
			}
			if (shop.getImage1() != null) {
				for (String s : shop.getImage1().split(",")) {
					if (s.length() > 0) {
						images.add(s);
					}
				}
			}
			if (shop.getImage3() != null) {
				for (String s : shop.getImage3().split(",")) {
					if (s.length() > 0) {
						images1.add(s);
					}
				}
			}
			mv.addObject("imageList", images);
			mv.addObject("imageList1", images1);
			try{
			DecimalFormat df = new DecimalFormat("######0.00");
			shop.setDiscount(df.format((1 - Double.parseDouble(shop.getDiscount())) * 100));
			}catch(Exception e){}
			
			mv.addObject("shop", shop);
		}
		return mv;
	}

	/**
	 * 验证账户名
	 * 
	 * @return
	 */
	@RequestMapping(value = "shop-name-re")
	public @ResponseBody String shop_name_re(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String name = request.getParameter("name");
		if (name != null && !"".equals(name)) {
			Integer count = apiShopsService.searByName(name);
			if (count > 0) {
				return "1";// 账户名已注册
			}
			// return "0";//未注册
		}
		return "0";// 未注册
	}

	/**
	 * 上传文件
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "shop-logo-upload")
	public void shop_logo_upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ModelMap model

		String path = ImageUtils.getServletWebAppsPath(request) + "/shops/";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String sdfStr = sdf.format(new Date());
		String fileName = sdfStr + "_" + file.getOriginalFilename();

		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		String logo_path = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 保存
		try {
			file.transferTo(targetFile);
			logo_path = ImageUtils.getDataBaseImagePath() + "/shops/" + fileName;

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "上传成功！");
			map.put("datas", logo_path);

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		//
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 上传缩略图
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "shop-smallpic-upload")
	public void goods_smallpic_upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ModelMap model

		String path = ImageUtils.getServletWebAppsPath(request) + "/shops/";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String sdfStr = sdf.format(new Date());
		String fileName = sdfStr + "_" + file.getOriginalFilename();

		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		String smallpic_path = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 保存
		try {
			file.transferTo(targetFile);
			smallpic_path = ImageUtils.getDataBaseImagePath() + "/shops/" + fileName;

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "上传成功！");
			map.put("datas", smallpic_path);

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		//
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 新增商户
	 * 
	 * @return
	 */
	@Transactional
	@RequestMapping(value = "shop-add")
	public void shop_add(String detailPic, String detailPic1, HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String c_uname = request.getParameter("c_uname");
		String c_pass = request.getParameter("c_pass");
		String c_sname = request.getParameter("c_sname");
		String c_address = request.getParameter("c_address");
		String c_ad = request.getParameter("c_ad");
		String c_des = request.getParameter("c_des");
		String c_main = request.getParameter("c_main");
		String c_tel = request.getParameter("c_tel");
		String c_mobi = request.getParameter("c_mobi");
		String c_hours = request.getParameter("c_hours");
		String c_service = request.getParameter("c_service");
		String c_fee = request.getParameter("c_fee");
		String c_bus = request.getParameter("c_bus");
		String c_map = request.getParameter("c_map");
		String c_web = request.getParameter("c_web");
		String c_mail = request.getParameter("c_mail");
		String c_qq = request.getParameter("c_qq");
		String c_city_id = request.getParameter("c_city_id");
		String c_p = request.getParameter("c_p");
		String c_city = request.getParameter("c_city");
		String c_area = request.getParameter("c_area");
		String c_quan = request.getParameter("c_quan");
		String c_zip = request.getParameter("c_zip");
		String c_type = request.getParameter("c_type");
		String c_logo = request.getParameter("c_logo");
		String c_vip = request.getParameter("c_vip");
		String c_appdate = request.getParameter("c_appdate");
		String c_ip = request.getParameter("c_ip");
		String c_mod = request.getParameter("c_mod");
		String c_jnum = request.getParameter("c_jnum");
		String c_grade = request.getParameter("c_grade");
		String c_hao = request.getParameter("c_hao");
		String c_dps = request.getParameter("c_dps");
		String c_enable = request.getParameter("c_enable");
		String c_check = request.getParameter("c_check");
		String c_order = request.getParameter("c_order");
		String c_psf = request.getParameter("c_psf");
		String c_comedate = request.getParameter("c_comedate");
		String is_open = request.getParameter("is_open");
		String is_auto_open = request.getParameter("is_auto_open");
		String is_push = request.getParameter("is_push");
		String start_fee = request.getParameter("start_fee");
		String average_shipping_time = request.getParameter("average_shipping_time");
		String longitude = request.getParameter("longitude");
		String latitude = request.getParameter("latitude");
		String devicetype = request.getParameter("devicetype");
		String deviceid = request.getParameter("deviceid");
		String image1 = detailPic;
		String image3 = detailPic1;
		String balance = request.getParameter("balance");
		String bankno = request.getParameter("bankno");
		String bankname = request.getParameter("bankname");
		String acceptname = request.getParameter("acceptname");
		String personid = request.getParameter("personid");
		String discount = request.getParameter("discount");
		String wxid = request.getParameter("wxid");
		String isziying = request.getParameter("isziying");
		String jwd = request.getParameter("jwd");
		String c_contacts = request.getParameter("c_contacts");
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		DecimalFormat df = new DecimalFormat("######0.00");
		String is_lunchbox = request.getParameter("is_lunchbox");
		String lunchbox_price = request.getParameter("lunchbox_price");
		String is_recieve_box_money = request.getParameter("is_recieve_box_money");
		String is_out = request.getParameter("is_out");
		String sort = request.getParameter("sort");

		try {
			if (id == null || (id.trim()).equals("")) {// add
				ApiShop t_shops = new ApiShop();
				String[] jw = new String[2];
				jw = jwd.split(",");
				t_shops.setcUname(c_uname);
				t_shops.setcPass(CipherUtil.generatePassword(c_pass));
				t_shops.setcSname(c_sname);
				t_shops.setcAddress(c_address);
				t_shops.setcAd(c_ad);
				t_shops.setcDes(c_des);
				t_shops.setcFee(c_fee);
				t_shops.setC_city_id(Integer.valueOf(c_city_id));
				t_shops.setcType(Integer.valueOf(c_type));
				t_shops.setcLogo(c_logo);
				t_shops.setcMobi(c_mobi);
				t_shops.setcAppdate(new Date());
				t_shops.setcOrder(0);
				t_shops.setcPsf(Integer.valueOf(c_psf));
				t_shops.setStart_fee(Integer.valueOf(start_fee));
				t_shops.setAverage_shipping_time(average_shipping_time);
				t_shops.setLongitude(Float.valueOf(jw[1]));
				t_shops.setLatitude(Float.valueOf(jw[0]));
				t_shops.setImage1(image1);
				t_shops.setImage3(image3);
				t_shops.setBalance(balance);
				t_shops.setBankno(bankno);
				t_shops.setBankname(bankname);
				t_shops.setAcceptname(acceptname);
				t_shops.setcQq(c_qq);
				t_shops.setcMail(c_mail);
				t_shops.setDiscount(df.format((100 - Double.parseDouble(discount)) / 100));
				t_shops.setPersonid(personid);
				t_shops.setWxid(wxid);
				t_shops.setIs_open(Integer.parseInt(is_open));
				t_shops.setIs_ziying(Integer.parseInt(isziying));
				t_shops.setcBus(c_bus);
				t_shops.setC_contacts(c_contacts);
				t_shops.setIs_lunchbox(Integer.valueOf(is_lunchbox));
				t_shops.setLunchbox_price(Double.valueOf(lunchbox_price));
				t_shops.setIs_out(Integer.parseInt(is_out));
				t_shops.setSort(Integer.valueOf(sort));
				if (is_recieve_box_money == null) {
					int is_recieve = 0;
					try {
						is_recieve = Integer.parseInt(is_recieve_box_money);
					} catch (Exception ex) {
					}
					t_shops.setIs_recieve_box_money(is_recieve);
				}

				apiShopsService.insertT_shops(t_shops);
				//
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "添加成功！");
			} else {//edit
				ApiShop t_shops = apiShopsService.findShopByCid(id);

				String[] jw = new String[2];
				jw = jwd.split(",");
				// t_shops.setcPass(Tools.toMD5(c_pass));
				t_shops.setcUname(c_uname);
				t_shops.setcPass(CipherUtil.generatePassword(c_pass));
				t_shops.setcSname(c_sname);
				t_shops.setcAddress(c_address);
				t_shops.setcAd(c_ad);
				t_shops.setcDes(c_des);
				t_shops.setcFee(c_fee);
				t_shops.setC_city_id(Integer.valueOf(c_city_id));
				t_shops.setcType(Integer.valueOf(c_type));
				t_shops.setcLogo(c_logo);
				t_shops.setcMobi(c_mobi);
				t_shops.setcAppdate(new Date());
				t_shops.setcOrder(0);
				t_shops.setcPsf(Integer.valueOf(c_psf));
				t_shops.setStart_fee(Integer.valueOf(start_fee));
				t_shops.setAverage_shipping_time(average_shipping_time);
				t_shops.setLongitude(Float.valueOf(jw[1]));
				t_shops.setLatitude(Float.valueOf(jw[0]));
				t_shops.setImage1(detailPic);
				t_shops.setImage3(detailPic1);
				t_shops.setBalance(balance);
				t_shops.setBankno(bankno);
				t_shops.setBankname(bankname);
				t_shops.setAcceptname(acceptname);
				t_shops.setcQq(c_qq);
				t_shops.setcMail(c_mail);
				t_shops.setDiscount(df.format((100 - Double.parseDouble(discount)) / 100));
				t_shops.setPersonid(personid);
				t_shops.setWxid(wxid);
				t_shops.setIs_open(Integer.parseInt(is_open));
				t_shops.setIs_ziying(Integer.parseInt(isziying));
				t_shops.setcBus(c_bus);
				t_shops.setC_contacts(c_contacts);
				t_shops.setIs_lunchbox(Integer.valueOf(is_lunchbox));
				t_shops.setLunchbox_price(Double.valueOf(lunchbox_price));
				t_shops.setIs_out(Integer.parseInt(is_out));
				t_shops.setSort(Integer.valueOf(sort));

				if (is_recieve_box_money == null) {
					int is_recieve = 0;
					try {
						is_recieve = Integer.parseInt(is_recieve_box_money);
					} catch (Exception ex) {
					}
					t_shops.setIs_recieve_box_money(is_recieve);
				}

				apiShopsService.updateT_shops(t_shops);
				//
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "编辑成功！");
			}

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		//
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 审核商户
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "shop-enable")
	public void shop_enable(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//
		String c_id = request.getParameter("c_id");
		String enable = request.getParameter("enable");
		Map<String, Object> map = new HashMap<String, Object>();
		// 保存
		try {
			ApiShop shop = apiShopsService.findShopByCid(c_id);
			shop.setcEnable(Integer.parseInt(enable));
			int ret_i = apiShopsService.updateT_shops(shop);

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "成功！");

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		//
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 商家公告
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "shopCad")
	public ModelAndView shopCad(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/shops_notice_list.jsp");
		List<Map<String, Object>> shops = new ArrayList<Map<String, Object>>();
		String sname = request.getParameter("sname");
		shops = apiShopsService.searShopCad(sname == null ? "" : sname);
		mv.addObject("sname", sname);
		mv.addObject("shops", shops);
		return mv;
	}

}
